import Vue from 'vue';
import VueRouter from 'vue-router';
import {routers} from './router';
import store from '../store';
import {toPost} from '../utils/MyAxios'
Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
  routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
  let username = localStorage.getItem("username");
  let password = localStorage.getItem("password");
  let loginTime = localStorage.getItem("loginTime");

  //已保存登录信息 且请求登录页面
  if(username && to.name === 'login'){
    if(loginTime){
      let day=Math.floor(Math.abs(new Date().getTime()-loginTime)/(24 * 3600 * 1000));
      //检验登录信息是否过期
      if(day>=7){
        next();
      }else{
        toPost("/authentication/login",{"username":username,"password":password})
          .then(res=>{
            if(res.resultCode===0){
              localStorage.setItem('nickname',res.data.nickname);
              localStorage.setItem('userId',res.data.userId);
              store.commit('MENUS', {'menus':res.data.menus});
            }
          });
        next({
          name: 'home'
        });
      }
    }else{
      next();
    }
  }else if(username && to.name === 'home'){
    toPost("/authentication/login",{"username":username,"password":password})
      .then(res=>{
        if(res.resultCode===0){
          localStorage.setItem('nickname',res.data.nickname);
          localStorage.setItem('userId',res.data.userId);
          store.commit('MENUS', {'menus':res.data.menus});
        }
      });
    next();
  }else if(!username && to.name !== 'login'){
    next({
      name: 'login'
    });
  }
  else{
    next();
  }
});
